package dbhandler;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ColumnUtil {
    public static Object convertColumn(String columnName, ResultSet rst, Field field) throws SQLException {
        //如果不是基本数据类型或者获取过来的值为null，直接返回null
        if (!field.getType().isPrimitive() && rst.getObject(columnName) == null) {
            return null;
        }
        Object value = null;
        //基本类型的判断
        if (field.getType().equals(String.class)) {
            value = rst.getString(columnName);
        } else if (field.getType().equals(Integer.class) || field.getType().equals(Integer.TYPE)) {
            value = rst.getInt(columnName);
        } else if (field.getType().equals(Short.class) || field.getType().equals(Short.TYPE)) {
            value = rst.getShort(columnName);
        } else if (field.getType().equals(Boolean.class) || field.getType().equals(Boolean.TYPE)) {
            value = rst.getBoolean(columnName);
        } else if (field.getType().equals(Long.class) || field.getType().equals(Long.TYPE)) {
            value = rst.getLong(columnName);
        } else if (field.getType().equals(Double.class) || field.getType().equals(Double.TYPE)) {
            value = rst.getDouble(columnName);
        } else if (field.getType().equals(Byte.class) || field.getType().equals(Byte.TYPE)) {
            value = rst.getByte(columnName);
        } else if (field.getType().equals(Float.class) || field.getType().equals(Float.TYPE)) {
            value = rst.getFloat(columnName);
        } else {
            value = rst.getObject(columnName);

        }

        return value;
    }

    private static Object toDate(Object value,Field f){
        //判断是不是java.util.Date的子类
        if (value instanceof java.util.Date){
            //获取字段对应的类型
            final String name = f.getType().getName();
            if ("java.sql.Date".equals(name)){
                value=new java.sql.Date(((java.util.Date) value).getTime());
            }else if ("java.sql.Time".equals(name)){
                value = new java.sql.Time(((java.util.Date) value).getTime());
            }
        }
        return value;
    }

}
